package com.wyw.shell.learning;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2024/3/29 17:43
 * Update History:
 * Author        Time            Content
 */
public class Test1 {
    public List<String> executeGetNumberShellScript() {

        List<String> strList = new ArrayList<String>();
        try {
            System.out.println("执行get_number脚本");
            // 执行命令，此处为执行的统计用户的shell脚本
            String command = "/Data/test2.sh";
            Process process = Runtime.getRuntime().exec(command);
            // 获取输出流
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 处理输出结果
                System.out.println("执行get_number脚本结果:" + line);
                strList.add(line);
            }
            // 等待进程执行完毕并退出
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Command '" + command + "' exited with code " + exitCode);
            }
            // 获取Shell脚本的返回值
            return strList;
        } catch (Exception e) {
            throw new RuntimeException("Failed to execute shell script: " + e.getMessage(), e);
        }
    }

    public void executeBackNumberShellScript() {
        try {
            System.out.println("执行number_file_back脚本");
            // 执行命令，此处为执行的统计用户的shell脚本
            String command = "/Data/test1.sh";
            Process process = Runtime.getRuntime().exec(command);
            // 获取输出流
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 处理输出结果
                System.out.println("执行number_file_back脚本结果:" + line);
            }
            // 等待进程执行完毕并退出    如果正常结束，exitCode返回0
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Command '" + command + "' exited with code " + exitCode);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to execute shell script: " + e.getMessage(), e);
        }
    }
}
